import { SearchOutlined } from '@ant-design/icons';
import { Button, Input, message, Space, Table } from 'antd';
import React, { useEffect, useState } from 'react';

// 引入 API 方法（根据你的实际接口修改）
import { queryOrderByPage, updateOrderStatus } from '@/services/swagger/orderController';

const DeliveryManagement: React.FC = () => {
  const [orders, setOrders] = useState<API.OrderVO[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [total, setTotal] = useState<number>(0);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(8);
  const [searchTerm, setSearchTerm] = useState<string>('');

  // 获取订单数据
  const fetchData = async () => {
    setLoading(true);
    try {
      const response = await queryOrderByPage({
        pageNo: currentPage,
        pageSize,
        number: searchTerm || undefined,
        status: 1, // 假设 1 是未配送状态
      });
      if (response && response.list) {
        setOrders(response.list);
        setTotal(response.total || 0);
      }
    } catch (error) {
      console.error('获取未配送订单失败:', error);
      message.error('获取订单失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [currentPage, pageSize, searchTerm]);

  // 处理完成配送
  const handleComplete = async (id: number) => {
    try {
      await updateOrderStatus({ id: id, status: 4 }); // 假设 4 是已完成状态
      message.success('配送完成');
      fetchData(); // 刷新数据
    } catch (error) {
      console.error('配送完成失败:', error);
    }
  };

  // 处理取消订单
  const handleCancel = async (id: number) => {
    try {
      await updateOrderStatus({ id: id, status: 3 }); // 假设 3 是已取消状态
      message.success('订单已取消');
      fetchData(); // 刷新数据
    } catch (error) {
      message.error('取消订单失败');
    }
  };

  // 表格列配置
  const columns = [
    {
      title: '订单号',
      dataIndex: 'number',
      key: 'number',
    },
    {
      title: '客户姓名',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '金额',
      dataIndex: 'totalFee',
      key: 'totalFee',
      render: (totalFee: number) => `¥${totalFee.toFixed(2)}`,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: API.OrderVO) => (
        <Space size="middle">
          <Button type="primary" onClick={() => handleComplete(record.id)}>
            完成配送
          </Button>
          <Button danger onClick={() => handleCancel(record.id)}>
            取消
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      {/* 搜索栏 */}
      <Input
        placeholder="输入订单号进行搜索"
        prefix={<SearchOutlined />}
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        style={{ width: '300px', marginBottom: 16 }}
      />

      {/* 表格主体 */}
      <Table
        columns={columns}
        dataSource={orders}
        loading={loading}
        rowKey="id"
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: total,
          showSizeChanger: true,
          onShowSizeChange: (_, size) => {
            setPageSize(size);
            setCurrentPage(1);
          },
          onChange: (page, size) => {
            setCurrentPage(page);
            setPageSize(size || pageSize);
          },
          showTotal: (total) => `共 ${total} 条订单`,
        }}
      />
    </div>
  );
};

export default DeliveryManagement;
